<template>
	<view class="content"><map id="myMap" style="width: 750rpx;height: 100vh" :show-location="true" :markers="markers" :polyline="polyline" @markertap="markertap"></map></view>
</template>

<script>
let myLatitude, myLongitude, map;
export default {
	data() {
		return {
			title: 'Hello',
			longitude: '',
			latitude: '',
			markers: [
				{
					longitude: 118.787295,
					latitude: 32.072073,
					label: {
						content: '位置'
					},
					id: 0
				},
				{
					longitude: 118.771502,
					latitude: 32.081382,
					id: 1
				},
				{
					longitude: 118.796908,
					latitude: 32.080655,
					id: 2
				},
				{
					longitude: 118.781802,
					latitude: 32.082837,
					id: 3
				}
			],
			polyline: [
				{
					points: [],
					width: 1
				}
			]
		};
	},
	mounted() {
		this.getMapContext();
	},
	onLoad() {
		this.getPosition();
	},
	methods: {
		getPosition() {
			uni.getLocation({
				type: 'gcj02',
				success: res => {
					const { latitude, longitude } = res;
					myLatitude = latitude;
					myLongitude = longitude;
					console.log(myLatitude, myLongitude);
					this.moveToMyPostition();
				},
				fail(err) {
					console.log(err);
				}
			});
		},
		getMapContext() {
			map = uni.createMapContext('myMap', this);
			this.includePoints();
			this.moveToMyPostition();
		},
		moveToMyPostition() {
			// if (map && myLatitude && myLongitude) {
			// 	map.moveToLocation({
			// 		longitude: myLongitude,
			// 		latitude: myLatitude,
			// 		fail: err => {
			// 			console.log(err);
			// 		},
			// 		success: res => {
			// 			console.log(res);
			// 		}
			// 	});
			// }
		},
		includePoints() {
			map.includePoints({
				points: this.markers
			});
		},
		markertap(e) {
			const current = this.markers.find(item => item.id === e.detail.markerId);
			if (current) {
				if (this.polyline[0].points.length > 0) {
					this.polyline[0].points.splice(0, 1, { latitude: current.latitude, longitude: current.longitude });
				} else {
					this.polyline[0].points.push({ latitude: current.latitude, longitude: current.longitude });
					this.polyline[0].points.push({ latitude: myLatitude, longitude: myLongitude });
				}
				console.log(this.polyline);
			}
		},
		path() {}
	}
};
</script>

<style>
.content {
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}

.logo {
	height: 200rpx;
	width: 200rpx;
	margin: 200rpx auto 50rpx auto;
}

.text-area {
	display: flex;
	justify-content: center;
}

.title {
	font-size: 36rpx;
	color: #8f8f94;
}
</style>
